package org.ontobrowser.ontoextract;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class RDFConversionUtil {
	
	public static List<Class> getClasses(String urlPath) throws SAXException, IOException, ParserConfigurationException
	{
		URL url = new URL(urlPath);
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	    dbf.setValidating(false);
	    dbf.setNamespaceAware(true);
	    dbf.setIgnoringElementContentWhitespace(true);

		// Parse the input to produce a parse tree with its root
		// in the form of a Document object
		Document doc = null;
		    
	    DocumentBuilder builder = dbf.newDocumentBuilder();
	    doc = builder.parse(url.openStream());
	    
	    Element element = doc.getDocumentElement();
	    
	    
	    
	    List<Class> clazzs = RDFConversionUtil.extractClass(element);
	    
	    
	    return clazzs;
	}
	
	public static List<Class> extractClass(Element document) {
		NodeList nodeList = RDFDomUtil.getClassElements(document);
		
		List<Class> classList = new ArrayList<Class>();
		
		for(int i=0; i<nodeList.getLength(); i++) {
	    	Element classElement = (Element)nodeList.item(i);
	    	Class clazz = convert((Element)classElement);
	    	
	    	Attr attr = classElement.getAttributeNodeNS(RDFDomUtil.RDF_NS, "about");
	    	String resource = attr.getValue();

		    List<Property> properties = RDFDomUtil.getElementProperies(resource, document);
		    
		    clazz.setProperties(properties);
	    	
	    	classList.add(clazz);
	    }
		
		return classList;
	}
	
	public static Class convert(Element element) {
		Class clazz = new Class(element);
		
		//RDFDomUtil.getHierarchicalProperies(element);
				
		return clazz;
	}
	

}
